package cn.com.rocketmq.batch;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.logging.org.slf4j.Logger;
import org.apache.rocketmq.logging.org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 批量消息
 * 优点：减少网络OA，提高吞吐量
 * 限制：
 *  消息大小不能超过4M
 *  相同的topic
 *  相同的waitStoreMsgOk
 *  不能是延迟消息、事务消息等
 * @author xuhaixiang
 * @date 2023-09-10
 */
public class Producer {

    /**
     * 日志对象
     */
    private static  final Logger logger = LoggerFactory.getLogger(Producer.class);


    public static void main(String[] args) {

        DefaultMQProducer producer = null;
        try {
            producer = new DefaultMQProducer("syncProducer");
            producer.setNamesrvAddr("192.168.113.101:9876");
            producer.start();
            List<Message> messages = new ArrayList<>();
            for (int i = 0; i < 2000; i++) {
                String body = i + "Lorem ipsum dolor sit amet consectetur adipisicing elit. Quasi exercitationem laudantium repellendus quisquam aspernatur est neque quidem vitae nostrum! Quia voluptatibus vitae tempore! Repellendus quam aspernatur, nam neque hic esse!";
                //参数一：主题、参数二：过滤、参数三：消息内容
                Message message = new Message("rocketmq_syncDemo","tag", body.getBytes("UTF-8"));
                messages.add(message);
            }
            ListSplitter listSplitter = new ListSplitter(messages);
            while (listSplitter.hasNext()) {
                List<Message> messageList = listSplitter.next();
                SendResult result = producer.send(messageList);
                String msgId = result.getMsgId();
                SendStatus sendStatus = result.getSendStatus();
                logger.info("{}消息发送状态为{}", msgId, sendStatus);
            }
        } catch (Exception e) {
            logger.error("生产者发送消息失败！" ,e);
        }

    }
}
